package com.xu.cloud.common.aop;

import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.StaticMethodMatcher;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * Servlet请求匹配切点
 * 类上有Controller注解, 包名以com.xu开始, 方法上有RequestMapping注解
 *
 * @author xuguan
 * @since 2025/1/13
 */
@SuppressWarnings("NullableProblems")
public class ServletRequestPointcut implements Pointcut {
    @Override
    public ClassFilter getClassFilter() {
        return new ClassFilter() {
            @Override
            public boolean matches(Class<?> cls) {
                return Objects.nonNull(AnnotationUtils.findAnnotation(cls, Controller.class))
                        && ClassUtils.getPackageName(cls).startsWith("com.xu");
            }
        };
    }

    @Override
    public MethodMatcher getMethodMatcher() {
        return new StaticMethodMatcher() {
            @Override
            public boolean matches(Method method, Class<?> targetClass) {
                return Objects.nonNull(AnnotationUtils.findAnnotation(method, RequestMapping.class));
            }
        };
    }
}
